package com.softserveinc.ita.kaiji.multiplay.service;

import com.softserveinc.ita.kaiji.multiplay.KaijiException;
import com.softserveinc.ita.kaiji.multiplay.dao.PlayerOnlineInfoDAO;
import com.softserveinc.ita.kaiji.multiplay.dao.RoomDAO;
import com.softserveinc.ita.kaiji.multiplay.domain.player.PlayerOnlineInfo;
import com.softserveinc.ita.kaiji.multiplay.domain.room.PlayRoom;
import com.softserveinc.ita.kaiji.multiplay.dto.client.DtoClient;
import com.softserveinc.ita.kaiji.multiplay.dto.server.DtoError;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.security.Principal;

/**
 * Project kaiji-game
 * Created by mikeldpl
 * 22.03.2015 14:41.
 */

@Service
public class PlayerService {

	private static final Logger LOG = Logger.getLogger(PlayerService.class);


	@Autowired
	public PlayerOnlineInfoDAO playerOnlineInfoDAO;
	@Autowired
	public RoomDAO roomDAO;
	@Autowired
	private ApplicationContext appContext;

	public void addPlayer(Principal principal, String simpSessionId, String shipName) {
		PlayRoom playRoom = roomDAO.findOne(shipName);
		if (playRoom != null) {
			PlayerOnlineInfo player = appContext.getBean(PlayerOnlineInfo.class, simpSessionId, principal.getName(), playRoom);
//            PlayerOnlineInfo player = new PlayerOnlineInfo(simpSessionId, principal.getName(), playRoom);
			try {
				if (player.goOnLina()) {
					playerOnlineInfoDAO.save(player);
				}
			} catch (RuntimeException ex) {
				ex.printStackTrace();
				throw new KaijiException(ex);
			}
		}
	}

	public void remove(String simpSessionId) {
		PlayerOnlineInfo player = playerOnlineInfoDAO.findOne(simpSessionId);
		if (player != null) {
			try {
				player.goOffLina();
			} catch (RuntimeException ex) {
				ex.printStackTrace();
				throw new KaijiException(ex);
			}
			playerOnlineInfoDAO.delete(player.getIdSession());
		}
	}

	public void inComeMessage(Principal principal, String simpSessionId, DtoClient msg) {
		PlayerOnlineInfo player = playerOnlineInfoDAO.findOne(simpSessionId);
		if (player != null) {
			try {
				player.getPlayRoom().inComeMessage(player, msg);
			} catch (RuntimeException ex) {
				ex.printStackTrace();
				player.send(new DtoError().setErr("SERVER ERROR: " + ex.getClass().getName() + " " + ex.getMessage()));
				throw new KaijiException(ex);
			}
		}
	}
}
